package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.AttractionComment;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.AttractionCommentQuery;
import cn.wolfcode.luowowo.comment.repository.AttractionCommentRepository;
import cn.wolfcode.luowowo.comment.service.IAttractionCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class AttractionCommentServiceImpl implements IAttractionCommentService {
    @Autowired
    private AttractionCommentRepository repository;

    //使用较为底层的贾琏欲执事, 实现mongodb操作, 这里用它来实现较为复杂操作
    @Autowired
    private MongoTemplate template;

    @Override
    public void saveOrUpdate(AttractionComment comment) {
        if(!StringUtils.hasLength(comment.getId())){
            //创建
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(AttractionCommentQuery qo) {
        //mongodb查询对象
        Query query = new Query();
        //查询条件
       if (qo.getAttrId() != -1L){
            Criteria criteria = Criteria.where("attrId").is(qo.getAttrId());
            query.addCriteria(criteria);
        }
        //查总数
        Long count = template.count(query, AttractionComment.class);
        //若总条数为空,无需再往下执行
        if (count == null){
            return Page.empty();
        }
        //qo.getPageSize();
        //分页对象
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, 5, Sort.Direction.DESC, "createTime");
        query.with(pageable);
        //查询当前页的数据
        List<AttractionComment> list = template.find(query, AttractionComment.class);
        return new PageImpl(list,pageable,count);
    }

    @Override
    public AttractionComment get(String pid) {
        return template.findById(pid, AttractionComment.class);
    }

    @Override
    public List<AttractionComment> getByUserId(Long uid) {
        List<AttractionComment> acs = repository.findByUserId(uid);
        return acs;
    }
}
